package com.atguigu.gmall.activity.controller;

import com.atguigu.gmall.activity.service.SeckillGoodsService;
import com.atguigu.gmall.activity.util.CacheHelper;
import com.atguigu.gmall.common.constant.MqConst;
import com.atguigu.gmall.common.result.Result;
import com.atguigu.gmall.common.result.ResultCodeEnum;
import com.atguigu.gmall.common.service.RabbitService;
import com.atguigu.gmall.common.util.AuthContextHolder;
import com.atguigu.gmall.common.util.DateUtil;
import com.atguigu.gmall.common.util.MD5;
import com.atguigu.gmall.model.activity.SeckillGoods;
import com.atguigu.gmall.model.activity.UserRecode;
import com.atguigu.gmall.product.client.ProductFeignClient;
import com.atguigu.gmall.user.client.UserFeignClient;
import org.apache.commons.lang.StringUtils;
import org.apache.http.auth.AUTH;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
 * @author Sanmier
 * @create 2020-12-23 20:52
 */
@RestController
@RequestMapping("/api/activity/seckill")
public class SeckillGoodsApiController {

    @Autowired
    private SeckillGoodsService seckillGoodsService;

    @Autowired
    private UserFeignClient userFeignClient;

    @Autowired
    private ProductFeignClient productFeignClient;

    @Autowired
    private RabbitService rabbitService;


    // 返回全部列表
    @GetMapping("/findAll")
    public Result findAll() {
        return Result.ok(seckillGoodsService.findAll());
    }


    // 获取实体
    @GetMapping("/getSeckillGoods/{skuId}")
    public Result getSeckillGoods(@PathVariable("skuId") Long skuId) {
        return Result.ok(seckillGoodsService.findSeckillGoodsById(skuId));
    }


    //获取下单吗
    @GetMapping("auth/getSeckillSkuIdStr/{skuId}")
    public Result getSeckillSkuIdStr(@PathVariable Long skuId, HttpServletRequest request){
        //  skuIdStr是啥？
        //  windows.location.href = '/seckill/queue.html?skuId=' + this.skuId + '&skuIdStr=' + skuIdStr
        //  返回下单码  放入result中
        //  下单码组成  对userId  进行md5加密
        String userId = AuthContextHolder.getUserId(request);

        //  什么时候获取下单码  在活动开始之后 结束之前获取
        //  获取到秒杀商品对象
        SeckillGoods seckillGoods = seckillGoodsService.findSeckillGoodsById(skuId);
        if (seckillGoods!=null){

            //生成下单码
            Date curTime = new Date();
            if (DateUtil.dateCompare(seckillGoods.getStartTime(), curTime) && DateUtil.dateCompare(curTime, seckillGoods.getEndTime())){

                //可以动态生成  放在redis缓存
                String skuIdStr = MD5.encrypt(userId);
                return Result.ok(skuIdStr);
            }
        }
        return Result.fail().message("获取下单码失败");
    }


    //保存订单  并非保存到数据库 只是将UserRecode数据发送到mq中
    //根据用户和商品ID实现秒杀下单
    @PostMapping("auth/seckillOrder/{skuId}")
    public Result seckillOrder(@PathVariable Long skuId, HttpServletRequest request){
        //先获取url传递的下单码
        String skuIdStr = request.getParameter("skuIdStr");
        //校验下单码  将用户userId进行MD5加密
        String userId = AuthContextHolder.getUserId(request);
        if (!skuIdStr.equals(MD5.encrypt(userId))){
            //非法请求
            return Result.build(null, ResultCodeEnum.SECKILL_ILLEGAL);
        }

        //校验状态位  存在在内存{map.put(skuId,1)}
        String stat = (String) CacheHelper.get(skuId.toString());
        //null,1,0
        if (StringUtils.isEmpty(stat)){
            return Result.build(null, ResultCodeEnum.SECKILL_ILLEGAL);
        }
        if ("1".equals(stat)){
            //还可以秒 将数据发送到mq中
            UserRecode userRecode = new UserRecode();
            userRecode.setUserId(userId);
            userRecode.setSkuId(skuId);

            //发送消息
            rabbitService.sendMessage(MqConst.EXCHANGE_DIRECT_SECKILL_USER, MqConst.ROUTING_SECKILL_USER, userRecode);
            //返回200
            return Result.ok(userRecode);
        }else {
            //已售罄
            return Result.build(null, ResultCodeEnum.SECKILL_FINISH);
        }
    }


    //检查抢购状态
    @GetMapping("auth/checkOrder/{skuId}")
    public Result checkOrder(@PathVariable Long skuId,HttpServletRequest request){
        //获取用户Id
        String userId = AuthContextHolder.getUserId(request);
        //返回数据
        return seckillGoodsService.checkOrder(skuId,userId);
    }


    //下单页面展示控制器
    @GetMapping("auth/trade")
    public Result trade(HttpServletRequest request){
        // 获取用户id
        String userId = AuthContextHolder.getUserId(request);
        return seckillGoodsService.seckillTrade(userId);
    }
}
